package com.ruoyi.system.service.impl;



import com.ruoyi.system.domain.RequestLog;
import com.ruoyi.system.service.RequestLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Collections;
import java.util.Map;

@Slf4j
@Service
public class ExternalApiService {
    private static final Logger logger = LoggerFactory.getLogger(ExternalApiService.class);
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    RequestLogService requstLogService;

/*
* url:请求地址
* method:请求方式
* params:请求参数
* body:请求体
* responseType:响应的数据类型
* headerParamsMap:请求头参数
*
* */
    public <T>T  callExternalApi(String url, HttpMethod method, Map<String,String> headerParamsMap, MultiValueMap<String, String> params , Object body, Class<T> responseType)  {

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    if (params != null) {
        builder.queryParams(params);
    }
    String finalUrl = builder.toUriString();
    logger.info("Sending request to URL: {}", finalUrl);

    HttpHeaders headers = new HttpHeaders();
    /*headers.setAccept(Collections.singletonList(acceptType));
    headers.setContentType(contentType);*/
    // 添加额外的请求头参数
    if (headerParamsMap != null) {
        headerParamsMap.forEach((key, value) -> headers.set(key, value));
    }
    logger.info("Request headers: {}", headers);
    logger.info("Request body: {}", body);
    // 创建HttpEntity，包含请求头和请求体
    HttpEntity<Object> request = (body != null) ? new HttpEntity<>(body, headers): new HttpEntity<>(headers);
    // 发送请求并获取响应
    long startTime = System.currentTimeMillis();
        LocalDateTime timestampStart = LocalDateTime.now();
        ResponseEntity<T> response=null;
        String  ex=null;
        try {
            response = restTemplate.exchange(
            builder.toUriString(),
            method,
            request,
            responseType
            );
           }catch (Exception e) {
           logger.error("调用外部接口异常", e);
           ex=e.getMessage();
       }finally {
            LocalDateTime timestampEnd = LocalDateTime.now();
            // 记录请求日志
            RequestLog requestLog = new RequestLog(finalUrl,method.toString(), body==null?null:body.toString(), params==null?null:params.toString(),timestampStart,timestampEnd, response==null?400:response.getStatusCode().value(), ex);
            requstLogService.save(requestLog);
        }
        long endTime = System.currentTimeMillis();
        logger.info("Received response from URL {} in {} ms", finalUrl, (endTime - startTime));
        if (response.getStatusCode().is2xxSuccessful()) {
            logger.info("Response status: {}, Body: {}", response.getStatusCode(), response.getBody().toString());
        } else {
            logger.warn("Response status: {}, Body: {}", response.getStatusCode(), response.getBody().toString());
        }

        return response.getBody();
    }
}
